package com.leetcode;

/**
 * 14. 最长公共前缀
 * 二分法
 */
public class Solution14_4 {

    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        int minLen = strs[0].length();
        for (String str : strs) {
            minLen = Math.min(minLen, str.length());
        }
        int left = 0;
        int right = minLen;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (!isCommonPrefix(strs, left, right)) {
                right = mid;
            } else {
                left = mid;
            }
        }
        return strs[0].substring(0, left);
    }

    private boolean isCommonPrefix(String[] strs, int left, int right) {
        int index = left;
        char ch = strs[0].charAt(index);
        while (index <= right) {
            for (String str : strs) {
                if (str.charAt(index) != ch) {
                    return false;
                }
            }
            index++;
        }
        return true;
    }

}
